package com.hydl.power.service.impl;

import com.hydl.power.mapper.*;
import com.hydl.power.pojo.*;
import com.hydl.power.service.IncomingCabinetService;
import com.hydl.power.utils.DateTimeUtils;
import com.hydl.power.utils.DateUtil;
import com.hydl.power.utils.ElectricityFeesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.*;
import java.util.*;

@Service
public class IncomingCabinetServiceImpl implements IncomingCabinetService {

    @Autowired
    private IncomingCabinetMapper incomingCabinetMapper;

    @Autowired
    private TransformerMapper transformerMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private PowerRoomMapper powerRoomMapper;

    @Autowired
    private OrderDeliveryMapper orderDeliveryMapper;

    @Autowired
    private InspectionOrderMapper inspectionOrderMapper;

    @Autowired
    private TemperatureDeviceMapper temperatureDeviceMapper;


  @Autowired
  private VacuumCircuitBreakerMapper vacuumCircuitBreakerMapper;  //高压真空断路器

  @Autowired
  private CurrentTransformerMapper currentTransformerMapper; //高压电流互感器

  @Autowired
  private MicrocomputerProtectionMapper microcomputerProtectionMapper;  //高压微机保护

  @Autowired
  private ArresterMapper arresterMapper;  //高压避雷器


  @Autowired
  private UniversalCircuitBreakerMapper universalCircuitBreakerMapper;   //低压万能式断路器

  @Autowired
  private CapacitanceMapper capacitanceMapper;   //低压电容

  @Autowired
  private LowVoltageTransformerMapper lowVoltageTransformerMapper;  //低压电流互感器

  @Autowired
  private LowVoltageCircuitBreakerMapper lowVoltageCircuitBreakerMapper;   //低压断路器

  @Autowired
  private DirectCurrentScreenMapper directCurrentScreenMapper;  //直流屏

  @Autowired
  private BatteryMapper batteryMapper;  //蓄电池

  @Autowired
  private ChargerModuleMapper chargerModuleMapper;  //充电模块



    @Autowired
    private TemperatureDataMapper temperatureDataMapper;

    @Autowired
    private PowerdataTimingMapper powerdataTimingMapper;

  @Override
  @Transactional
  public List<Map> queryIncoming(String time, String deviceId) throws ParseException{
    List<Map> listData = new ArrayList<>();
    Map map = new HashMap();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Transformer transformer=transformerMapper.queryTransformerByDeviceId(deviceId);

    int month=0;
    String transformerCapacity ="";
    String transformerName ="";
    if(transformer!=null){
      Date dt2 =sdf.parse(transformer.getInstallTime());
      Date dt1 =new Date();
      Calendar  from  =  Calendar.getInstance();
      from.setTime(dt2);
      Calendar  to  =  Calendar.getInstance();
      to.setTime(dt1);
      //只要年月
      int fromYear = from.get(Calendar.YEAR);
      int fromMonth = from.get(Calendar.MONTH);
      int toYear = to.get(Calendar.YEAR);
      int toMonth = to.get(Calendar.MONTH);
       month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
      transformerCapacity=transformer.getTransformerCapacity();
      transformerName=transformer.getDeviceName();
    }

    List<IncomingCabinet> list = incomingCabinetMapper.queryIncoming(time,deviceId);
    if(list.size()!=0){
      for (IncomingCabinet incomingCabinet : list) {
        map.put("deviceName",incomingCabinet.getDeviceName());
        map.put("deviceId",incomingCabinet.getDeviceId());
        map.put("pa",incomingCabinet.getPa());
        map.put("pb",incomingCabinet.getPb());
        map.put("pc",incomingCabinet.getPc());
        map.put("pt",incomingCabinet.getPt());
        map.put("createTime",sdf.format(incomingCabinet.getCreateTime()));
        if(incomingCabinet.getDeviceName().equals(transformerName) && transformer!=null){
          map.put("transformerCapacity",transformerCapacity);
          map.put("installTime",month);
        }else {
          listData=new ArrayList<>();
          return listData;
        }
        listData.add(map);
        map=new HashMap();
      }
    }

    return listData;
  }

  @Override
  public List<Map> queryYesterdayIncoming(String time,String deviceId) throws ParseException {
    List<Map> listData = new ArrayList<>();
    Map map = new HashMap();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Transformer transformer=transformerMapper.queryTransformerByDeviceId(deviceId);

    int month=0;
    String transformerCapacity ="";
    String transformerName ="";
    if(transformer!=null){
      Date dt2 =sdf.parse(transformer.getInstallTime());
      Date dt1 =new Date();
      Calendar  from  =  Calendar.getInstance();
      from.setTime(dt2);
      Calendar  to  =  Calendar.getInstance();
      to.setTime(dt1);
      //只要年月
      int fromYear = from.get(Calendar.YEAR);
      int fromMonth = from.get(Calendar.MONTH);
      int toYear = to.get(Calendar.YEAR);
      int toMonth = to.get(Calendar.MONTH);
      month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
      transformerCapacity=transformer.getTransformerCapacity();
      transformerName=transformer.getDeviceName();
    }

    List<IncomingCabinet> list = incomingCabinetMapper.queryYesterdayIncoming(time,deviceId);
    if(list.size()!=0){
      for (IncomingCabinet incomingCabinet : list) {
        map.put("deviceName",incomingCabinet.getDeviceName());
        map.put("deviceId",incomingCabinet.getDeviceId());
        map.put("pa",incomingCabinet.getPa());
        map.put("pb",incomingCabinet.getPb());
        map.put("pc",incomingCabinet.getPc());
        map.put("pt",incomingCabinet.getPt());
        map.put("createTime",sdf.format(incomingCabinet.getCreateTime()));
        if(incomingCabinet.getDeviceName().equals(transformerName) && transformer!=null){
          map.put("transformerCapacity",transformerCapacity);
          map.put("installTime",month);
        }else {
          listData=new ArrayList<>();
          return listData;
        }
        listData.add(map);
        map=new HashMap();
      }
    }

    return listData;
  }

  @Override
  public List<IncomingCabinet> queryeTheSameDayPower(String token, String strartTime) {
    SysUser sysUser = sysUserMapper.getUserByToken(token);
    if(sysUser!=null){
      if(sysUser.getStatus()==2){
        List<IncomingCabinet> list = incomingCabinetMapper.queryeTheSameDayPower(sysUser.getProjectId().toString(),strartTime);
        if(list.size()!=0){
          return list;
        }
      }
    }
    return null;
  }

  //用户报告
  @Override
  public Map<String,Object>  userReport(String projectId,String projectName, String startTime) {
      Project project = projectMapper.queryProjectByProId(projectId);

      if(Integer.parseInt(project.getPowerDaraFlag())==1){
        int deviceCount=0;
        Map<String,Object>  one = new HashMap();
        List list = new ArrayList();
        int transformer = incomingCabinetMapper.queryTransformerCount(projectId); //查询变压器数量
        String dgaugingPointCount=deviceMapper.getDeviceNumberByProjectId(projectId);//查询设备数量
        String SumTransformerCapacity =transformerMapper.queryTransformerCapacity(projectId); //查询配电房变压器总容量
        if(Integer.parseInt(dgaugingPointCount)-transformer>0){
          deviceCount =Integer.parseInt(dgaugingPointCount)-transformer;
        }
        if(SumTransformerCapacity==null){
          SumTransformerCapacity="0";
        }
        one.put("deviceCount",deviceCount);
        one.put("projectName",projectName);
        one.put("dataTime",startTime);
        one.put("dgaugingPointCount",dgaugingPointCount);
        one.put("SumTransformerCapacity",SumTransformerCapacity);
        one.put("transformer",transformer);
        list.add(one);
        return one;
      }
        int deviceCount=0;
        Map<String,Object>  two = new HashMap();
        List list = new ArrayList();
        int transformer = incomingCabinetMapper.queryTransformerCount(projectId); //查询变压器数量

        String dgaugingPointCount=temperatureDeviceMapper.getTemperatureDeviceCount(projectId);//查询设备数量

        String SumTransformerCapacity =transformerMapper.queryTransformerCapacity(projectId); //查询配电房变压器总容量
        if(Integer.parseInt(dgaugingPointCount)-transformer>0){
          deviceCount =Integer.parseInt(dgaugingPointCount)-transformer;
        }
        if(SumTransformerCapacity==null){
          SumTransformerCapacity="0";
        }
          two.put("deviceCount",deviceCount);
          two.put("projectName",projectName);
          two.put("dataTime",startTime);
          two.put("dgaugingPointCount",dgaugingPointCount);
          two.put("SumTransformerCapacity",SumTransformerCapacity);
          two.put("transformer",transformer);
        list.add(two);
        return two;

  }

        //同比/环比
        @Override
        public Map linkRelativeRatio(String projectId, String startTime) throws ParseException {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
          DecimalFormat df = new DecimalFormat("0.00%");
          Map<String,String> map = new HashMap<>();
          float str=0;
          float strs=0;
          DateTimeUtils dateTimeUtils = new DateTimeUtils();
          Project project = projectMapper.queryProjectByProId(projectId);

          Date date = sdf.parse(startTime);
          //环比时间
          Calendar calendar = Calendar.getInstance();
          calendar.setTime(date);
          calendar.add(Calendar.YEAR, -1);//当前时间减去一年，即一年前的时间
          //同比时间
          Calendar calendar1 = Calendar.getInstance();
          calendar1.setTime(date);
          calendar1.add(Calendar.MONTH, -1);//当前时间前去一个月，即一个月前的时间


            String monthPowerData  = incomingCabinetMapper.queryMonthPowerDataByRprojectId(projectId,startTime);
            if(monthPowerData==null){
              monthPowerData="0";
            }
            //同比
            String yearOnYear  = incomingCabinetMapper.queryMonthPowerDataByRprojectId(projectId,dateTimeUtils.getFormatYM(calendar.getTime()));
            if(yearOnYear==null){
              yearOnYear="0";
            }
            //环比
            String comparison  = incomingCabinetMapper.queryMonthPowerDataByRprojectId(projectId,dateTimeUtils.getFormatYM(calendar1.getTime()));
            if(comparison==null){
              comparison="0";
            }
            //同比公式
            if(Float.parseFloat(monthPowerData) < Float.parseFloat(yearOnYear)){
                   str = (Float.parseFloat(yearOnYear) - Float.parseFloat(monthPowerData)) / Float.parseFloat(yearOnYear);
            }else {
              str = (Float.parseFloat(monthPowerData) - Float.parseFloat(yearOnYear)) / Float.parseFloat(yearOnYear);
            }
            if(String.valueOf(str).equals("Infinity") || String.valueOf(str).equals("NaN") ){
              map.put("yearOnYearLoad", "100%");
            }else {
              map.put("yearOnYearLoad", df.format(str));
            }

            //环比公式
            strs = (Float.parseFloat(monthPowerData) - Float.parseFloat(comparison)) / Float.parseFloat(comparison);
            if(String.valueOf(strs).equals("Infinity") || String.valueOf(strs).equals("NaN")){
              map.put("comparisonLoad", "100%");
            }else {
              map.put("comparisonLoad",df.format(strs));
            }
            map.put("monthPowerData",monthPowerData);
            map.put("monthTime",startTime);
            map.put("yearOnYear",yearOnYear);
            map.put("yearTime",dateTimeUtils.getFormatYM(calendar.getTime()));
            map.put("comparison",comparison);
            map.put("comparisonTime",dateTimeUtils.getFormatYM(calendar1.getTime()));
            return map;

        }


  /**
   * 设备生命周期
   * @param projectId
   * @return
   */
  @Override
  public List<CabinetDevice> getDeviceLifeCycle(String projectId) {

    List<CabinetDevice> universalCircuitBreakerList = universalCircuitBreakerMapper.getDeviceByProjectId(projectId); //万能式断路器
    List<CabinetDevice> capacitanceList = capacitanceMapper.getDeviceByProjectId(projectId); //电容
    List<CabinetDevice> lowVoltageTransformerList = lowVoltageTransformerMapper.getDeviceByProjectId(projectId); //回路互感器
    List<CabinetDevice> lowVoltageCircuitBreakerList = lowVoltageCircuitBreakerMapper.getDeviceByProjectId(projectId); //回路断路器

    List<CabinetDevice> vacuumCircuitBreakerList = vacuumCircuitBreakerMapper.getDeviceByProjectId(projectId); //真空断路器
    List<CabinetDevice> currentTransformerList = currentTransformerMapper.getDeviceByProjectId(projectId); //电流互感器
    List<CabinetDevice> microcomputerProtectionList = microcomputerProtectionMapper.getDeviceByProjectId(projectId); //微机保护
    List<CabinetDevice> arresterList = arresterMapper.getDeviceByProjectId(projectId); //避雷器

    List<CabinetDevice> directCurrentScreenList = directCurrentScreenMapper.getDeviceByProjectId(projectId); //直流屏
    List<CabinetDevice> batteryList = batteryMapper.getDeviceByProjectId(projectId); //蓄电池
    List<CabinetDevice> chargerModuleList = chargerModuleMapper.getDeviceByProjectId(projectId); //充电模块

    List<CabinetDevice>  list=new ArrayList<>();
    list.addAll(universalCircuitBreakerList);
    list.addAll(capacitanceList);
    list.addAll(lowVoltageTransformerList);
    list.addAll(lowVoltageCircuitBreakerList);
    list.addAll(vacuumCircuitBreakerList);
    list.addAll(currentTransformerList);
    list.addAll(microcomputerProtectionList);
    list.addAll(arresterList);
    list.addAll(directCurrentScreenList);
    list.addAll(batteryList);
    list.addAll(chargerModuleList);

    return list;
  }


  /**
   * 用电分析
   * @param projectId
   * @param time
   * @return
   */
  @Override
  public List<DeviceAlarm> getDeviceAlarm(String projectId,String time) {

    List<DeviceAlarm> list = orderDeliveryMapper.getDeviceAlarm(projectId,time);

    return list;
  }


  @Override
  public List queryeEveryDayPower(String projectId, String startTime, String endTime) throws ParseException {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date dd = df.parse(endTime);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dd);
    calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天

    DateTimeUtils dateTimeUtils = new DateTimeUtils();
    List listdata = new ArrayList();

    List<IncomingCabinet> list = new ArrayList<>();

        list = incomingCabinetMapper.queryeEveryDayPower(projectId,startTime,df.format(calendar.getTime()));

        if(list!=null && !list.isEmpty()){
        for (IncomingCabinet incomingCabinet : list) {
          Map map = new HashMap();
          map.put("createTime",dateTimeUtils.getFormats(incomingCabinet.getCreateTime()));
          map.put("forwar",incomingCabinet.getForwardActiveTotalElectricalEnergy());
          listdata.add(map);
        }
        return listdata;
        }
    return listdata;
  }

  @Override
  public List queryePowerPermutation(String projectId,String startTime) throws ParseException {
    Project project=  projectMapper.queryProjectByProId(projectId);
    Map map=new HashMap();
    List data = new ArrayList();
    if(project == null){
      return data;
    }
      if(Integer.parseInt(project.getPowerDaraFlag()) == 1){
        if(project.getTableName()==null){
          return new ArrayList();
        }
        List<Powerdata> list = powerdataMapper.queryePowerPermutation( project.getTableName(), startTime);
        for (Powerdata powerdata : list) {
          map=new HashMap();
          map.put("deviceName",powerdata.getDeviceName());
          map.put("forwardActiveTotalElectricalEnergy",powerdata.getForwardActiveTotalElectricalEnergy());
          data.add(map);
        }
        return data;
      }
      if(project.getTemperatureDataTableName()==null){
        return new ArrayList();
      }
      List<TemperatureData> list=temperatureDataMapper.queryeTemperature(project.getTemperatureDataTableName(), startTime);
      for (TemperatureData temperatureData : list) {
        map=new HashMap();
          map.put("deviceName",temperatureData.getDeviceName());
          map.put("forwardActiveTotalElectricalEnergy",temperatureData.gettActiveEnergy());
          data.add(map);
    }
    return data;
  }

  @Override
  public List<IncomingCabinet> queryeTransformerPt(String projectId, String startTime) throws ParseException {
    List<Transformer> transformer = transformerMapper.queryTransformerProjectId(projectId);
    List<IncomingCabinet> list = incomingCabinetMapper.queryeTransformerPt(projectId,startTime);
    List list1 = new ArrayList();
    Map map = new HashMap();

    for (IncomingCabinet incomingCabinet : list) {
      for (Transformer transformer1 : transformer) {
          if(incomingCabinet.getDeviceName().equals(transformer1.getDeviceName())){
            map=new HashMap();
            map.put("deviceName",incomingCabinet.getDeviceName());
            map.put("max",incomingCabinet.getMax());
            map.put("min",incomingCabinet.getMin());
            map.put("avg",incomingCabinet.getAvg());
            map.put("capacity",transformer1.getTransformerCapacity());
            list1.add(map);
          }
      }
    }
    return list1;
  }

  @Override
  public List queryeLoadAnalysis(String projectId, String startTime) throws ParseException {
    long str = Long.valueOf(DateUtil.dateToStamp(startTime));
    DateTimeUtils dateTimeUtils = new DateTimeUtils();
    PowerdataTiming powerdataTimings = new PowerdataTiming();
    DecimalFormat df = new DecimalFormat("0.00%");
      List<Device> device = deviceMapper.getDeviceByProjectId(projectId);
      List<PowerdataTiming> listdata=new ArrayList();
      List listdatas=new ArrayList();

      float count = 0;
      float avgLoad = 0;

      Map maps=new HashMap();
      for (Device devices : device) {
        if(devices.getDeviceName().contains("变压器")){
          if(DateUtil.isThisMonth(str)){
            Powerdata powerdata = powerdataMapper.queryPowerDataOneDay(devices.getTableName(),devices.getSerialNumber());
            if(powerdata!=null){
              powerdataTimings.setMaxPt(powerdata.getMax_pt());
              powerdataTimings.setMinPt(powerdata.getMin_pt());
              powerdataTimings.setPtin(powerdata.getPtin());
              powerdataTimings.setAvgPt(powerdata.getAvg_pt());
              powerdataTimings.setCreatetime(dateTimeUtils.getFormat(powerdata.getCreatetime()));
            }else {
               return listdatas;
            }
          }
          List<PowerdataTiming> list = powerdataTimingMapper.queryePowerdataByProjectId(devices.getSerialNumber(),startTime);
            if(DateUtil.isThisMonth(str)){
              list.add(powerdataTimings);
            }
          List<Transformer> transformer = transformerMapper.queryTransformerProjectId(devices.getProjectId());
          for (Transformer transformer1 : transformer) {
            if(devices.getDeviceName().equals(transformer1.getDeviceName())) {
              maps=new HashMap();
              for (PowerdataTiming powerdataTiming : list) {
                powerdataTiming.setLoad(
                        Float.valueOf(df.format(powerdataTiming.getPtin()*1.732/Double.parseDouble(transformer1.getTransformerCapacity())).replace("%","")));
                count++;
                avgLoad=avgLoad+ Float.valueOf(df.format(powerdataTiming.getPtin()*1.732/Double.parseDouble(transformer1.getTransformerCapacity())).replace("%",""));
                listdata.add(powerdataTiming);

              }
              if(list.size() != 0){
                maps.put("list",listdata);
              }else {
                break;
              }

              //排序
              Collections.sort(listdata,new Comparator<PowerdataTiming>() {
                @Override
                public int compare(PowerdataTiming o1, PowerdataTiming o2) {
                  // TODO Auto-generated method stub
                  return o2.getMaxPt().intValue() - o1.getMaxPt().intValue() ;
                }
              });
              maps.put("maxPt",listdata.get(0).getMaxPt());
              maps.put("maxPtTime",listdata.get(0).getCreatetime());
              maps.put("minPt",listdata.get(list.size()-1).getMaxPt());
              maps.put("minPtTime",listdata.get(list.size()-1).getCreatetime());
              maps.put("capacity",transformer1.getTransformerCapacity());
              maps.put("deviceName",transformer1.getDeviceName());
              //平均pt排序
              Collections.sort(listdata,new Comparator<PowerdataTiming>() {
                @Override
                public int compare(PowerdataTiming o1, PowerdataTiming o2) {
                  // TODO Auto-generated method stub
                  return o2.getAvgPt().intValue() - o1.getAvgPt().intValue() ;
                }
              });
              maps.put("avgPt",listdata.get(0).getAvgPt());

              //负载率排序
              Collections.sort(listdata,new Comparator<PowerdataTiming>() {
                @Override
                public int compare(PowerdataTiming o1, PowerdataTiming o2) {
                  // TODO Auto-generated method stub
                  return o2.getLoad().intValue() - o1.getLoad().intValue() ;
                }
              });
              maps.put("avgLoad",avgLoad/count);
              maps.put("maxLoad",listdata.get(0).getLoad());

            }
          }
          count=0;
          avgLoad=0;
          if(!maps.isEmpty()){
            listdatas.add(maps);
          }
          listdata=new ArrayList();
        }
      }
    return listdatas;
  }



  @Override
  public Map queryOrderCount(String projectId, String startTime, String endTime) throws ParseException {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    Date dd = df.parse(endTime);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(dd);
    calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天

    int orderDelivery=orderDeliveryMapper.queryOrderCount(projectId,startTime,df.format(calendar.getTime()));
    int inspectionOrder=inspectionOrderMapper.queryInspectionOrderCount(projectId,startTime,df.format(calendar.getTime()));

    Map map = new HashMap();
    map.put("orderDelivery",orderDelivery);
    map.put("inspectionOrder",inspectionOrder);
    return map;
  }


  @Autowired
  private ElectricityFeesMapper electricityFeesMapper;

  @Autowired
  private PowerdataMapper powerdataMapper;


  @Override
  public Map<String, Object>  getMonthElectricityBill(String projectId, String year,String time) {
    Project project = projectMapper.queryProjectByProId (projectId);
    ElectricityFees electricityFees = electricityFeesMapper.getElectricityFeesByTime(project.getElectricityFeesType(), year);


    Map<String, Object> resultMap=new HashMap<>();

    //查询进线柜变压器电量
    List<ElectricityBill> list = powerdataMapper.getMonthElectricityBill(projectId,time);

    if (list.size()>0){


      Map<String, List<ElectricityBill>> map = new HashMap<>();
      for (ElectricityBill electricityBill : list){
        if (map.containsKey(electricityBill.getDeviceId())){
          map.get(electricityBill.getDeviceId()).add(electricityBill);
        }else{
          List<ElectricityBill> newList = new ArrayList<>();
          newList.add(electricityBill);
          map.put(electricityBill.getDeviceId(), newList);
        }
      }


      List<ElectricityBill> electricityList=new ArrayList<>();
      for(Map.Entry<String, List<ElectricityBill>> entry : map.entrySet()){
        entry.getValue().sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));
        for(int i=0;i<entry.getValue().size();i++){
          ElectricityBill electricityBill = entry.getValue().get(i);
          if (i+1<entry.getValue().size()){
            electricityBill.setForwardActiveTotalElectricalEnergy(entry.getValue().get(i+1).getMinForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
          }else{
            electricityBill.setForwardActiveTotalElectricalEnergy(electricityBill.getMaxForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
          }
        }
        electricityList.addAll(entry.getValue());
      }


      Map<String, List<ElectricityBill>> electricityBillMap = new HashMap<>();
      for (ElectricityBill electricityBill : electricityList){
        if (electricityBillMap.containsKey(electricityBill.getTime())){
          electricityBillMap.get(electricityBill.getTime()).add(electricityBill);
        }else{
          List<ElectricityBill> newList = new ArrayList<>();
          newList.add(electricityBill);
          electricityBillMap.put(electricityBill.getTime(), newList);
        }
      }



      List<ElectricityBill> electricityBillList=new ArrayList<>();
      for(Map.Entry<String, List<ElectricityBill>> entry : electricityBillMap.entrySet()){
        ElectricityBill electricity=new ElectricityBill();
        double priceNumber=0;
        double forwardActiveTotalElectricalEnergy=0;
        List<ElectricityBill> electricityBills = entry.getValue();
        for (ElectricityBill electricityBill:electricityBills ){
          electricity.setTime(electricityBill.getTime());
          double v = electricityBill.getForwardActiveTotalElectricalEnergy() * electricityFees.getPrice();
          priceNumber += v;
          forwardActiveTotalElectricalEnergy+=electricityBill.getForwardActiveTotalElectricalEnergy();
        }
        electricity.setPrice(priceNumber);
        electricity.setForwardActiveTotalElectricalEnergy(forwardActiveTotalElectricalEnergy);
        electricityBillList.add(electricity);
      }
      electricityBillList.sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));

      double totalPrice =0;
      double totalElectricQuantity=0;
      for (ElectricityBill electricityBill:electricityBillList){
        totalPrice+=electricityBill.getPrice();
        totalElectricQuantity+=electricityBill.getForwardActiveTotalElectricalEnergy();
      }

      resultMap.put("list",electricityBillList);
      resultMap.put("price",electricityFees.getPrice());
      resultMap.put("totalPrice",totalPrice);
      resultMap.put("totalElectricQuantity",totalElectricQuantity);

      return resultMap;
    }else if (project.getPowerDaraFlag().equals("2")){
      //查询电器火灾电量
      if (project.getTemperatureDataTableName()==null){
        return null;
      }
      List<ElectricityBill> temperatureDataList = temperatureDataMapper.getMonthElectricityBill(time,project.getTemperatureDataTableName());
      if (temperatureDataList.size()>0){
        Map<String, List<ElectricityBill>> map = new HashMap<>();
        for (ElectricityBill electricityBill : temperatureDataList){
          if (map.containsKey(electricityBill.getDeviceId())){
            map.get(electricityBill.getDeviceId()).add(electricityBill);
          }else{
            List<ElectricityBill> newList = new ArrayList<>();
            newList.add(electricityBill);
            map.put(electricityBill.getDeviceId(), newList);
          }
        }


        List<ElectricityBill> electricityList=new ArrayList<>();
        for(Map.Entry<String, List<ElectricityBill>> entry : map.entrySet()){
          entry.getValue().sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));
          for(int i=0;i<entry.getValue().size();i++){
            ElectricityBill electricityBill = entry.getValue().get(i);
            if (i+1<entry.getValue().size()){
              electricityBill.setForwardActiveTotalElectricalEnergy(entry.getValue().get(i+1).getMinForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
            }else{
              electricityBill.setForwardActiveTotalElectricalEnergy(electricityBill.getMaxForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
            }
          }
          electricityList.addAll(entry.getValue());
        }


        Map<String, List<ElectricityBill>> electricityBillMap = new HashMap<>();
        for (ElectricityBill electricityBill : electricityList){
          if (electricityBillMap.containsKey(electricityBill.getTime())){
            electricityBillMap.get(electricityBill.getTime()).add(electricityBill);
          }else{
            List<ElectricityBill> newList = new ArrayList<>();
            newList.add(electricityBill);
            electricityBillMap.put(electricityBill.getTime(), newList);
          }
        }



        List<ElectricityBill> electricityBillList=new ArrayList<>();
        for(Map.Entry<String, List<ElectricityBill>> entry : electricityBillMap.entrySet()){
          ElectricityBill electricity=new ElectricityBill();
          double priceNumber=0;
          double forwardActiveTotalElectricalEnergy=0;
          List<ElectricityBill> electricityBills = entry.getValue();
          for (ElectricityBill electricityBill:electricityBills ){
            electricity.setTime(electricityBill.getTime());
            double v = electricityBill.getForwardActiveTotalElectricalEnergy() * electricityFees.getPrice();
            priceNumber += v;
            forwardActiveTotalElectricalEnergy+=electricityBill.getForwardActiveTotalElectricalEnergy();
          }
          electricity.setPrice(priceNumber);
          electricity.setForwardActiveTotalElectricalEnergy(forwardActiveTotalElectricalEnergy);
          electricityBillList.add(electricity);
        }
        electricityBillList.sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));

        double totalPrice =0;
        double totalElectricQuantity=0;
        for (ElectricityBill electricityBill:electricityBillList){
          totalPrice+=electricityBill.getPrice();
          totalElectricQuantity+=electricityBill.getForwardActiveTotalElectricalEnergy();
        }

        resultMap.put("list",electricityBillList);
        resultMap.put("price",electricityFees.getPrice());
        resultMap.put("totalPrice",totalPrice);
        resultMap.put("totalElectricQuantity",totalElectricQuantity);

        return resultMap;

      }
    }else if(project.getPowerDaraFlag().equals("1")){
      if(project.getTableName()==null){
        return null;
      }
      //查询多功能表电量
      List<ElectricityBill> powerDataList = powerdataMapper.getMonthElectricityBillByTableName(time,project.getTableName());
      if (powerDataList.size()>0){
        Map<String, List<ElectricityBill>> map = new HashMap<>();
        for (ElectricityBill electricityBill : powerDataList){
          if (map.containsKey(electricityBill.getDeviceId())){
            map.get(electricityBill.getDeviceId()).add(electricityBill);
          }else{
            List<ElectricityBill> newList = new ArrayList<>();
            newList.add(electricityBill);
            map.put(electricityBill.getDeviceId(), newList);
          }
        }


        List<ElectricityBill> electricityList=new ArrayList<>();
        for(Map.Entry<String, List<ElectricityBill>> entry : map.entrySet()){
          entry.getValue().sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));
          for(int i=0;i<entry.getValue().size();i++){
            ElectricityBill electricityBill = entry.getValue().get(i);
            if (i+1<entry.getValue().size()){
              electricityBill.setForwardActiveTotalElectricalEnergy(entry.getValue().get(i+1).getMinForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
            }else{
              electricityBill.setForwardActiveTotalElectricalEnergy(electricityBill.getMaxForwardActiveTotalElectricalEnergy()-electricityBill.getMinForwardActiveTotalElectricalEnergy());
            }
          }
          electricityList.addAll(entry.getValue());
        }


        Map<String, List<ElectricityBill>> electricityBillMap = new HashMap<>();
        for (ElectricityBill electricityBill : electricityList){
          if (electricityBillMap.containsKey(electricityBill.getTime())){
            electricityBillMap.get(electricityBill.getTime()).add(electricityBill);
          }else{
            List<ElectricityBill> newList = new ArrayList<>();
            newList.add(electricityBill);
            electricityBillMap.put(electricityBill.getTime(), newList);
          }
        }



        List<ElectricityBill> electricityBillList=new ArrayList<>();
        for(Map.Entry<String, List<ElectricityBill>> entry : electricityBillMap.entrySet()){
          ElectricityBill electricity=new ElectricityBill();
          double priceNumber=0;
          double forwardActiveTotalElectricalEnergy=0;
          List<ElectricityBill> electricityBills = entry.getValue();
          for (ElectricityBill electricityBill:electricityBills ){
            electricity.setTime(electricityBill.getTime());
            double v = electricityBill.getForwardActiveTotalElectricalEnergy() * electricityFees.getPrice();
            priceNumber += v;
            forwardActiveTotalElectricalEnergy+=electricityBill.getForwardActiveTotalElectricalEnergy();
          }
          electricity.setPrice(priceNumber);
          electricity.setForwardActiveTotalElectricalEnergy(forwardActiveTotalElectricalEnergy);
          electricityBillList.add(electricity);
        }
        electricityBillList.sort((t1, t2) -> t1.getTime().compareTo(t2.getTime()));

        double totalPrice =0;
        double totalElectricQuantity=0;
        for (ElectricityBill electricityBill:electricityBillList){
          totalPrice+=electricityBill.getPrice();
          totalElectricQuantity+=electricityBill.getForwardActiveTotalElectricalEnergy();
        }

        resultMap.put("list",electricityBillList);
        resultMap.put("price",electricityFees.getPrice());
        resultMap.put("totalPrice",totalPrice);
        resultMap.put("totalElectricQuantity",totalElectricQuantity);

        return resultMap;
      }


    }
    return null;

  }


  @Override
  public Map queryePowerFactor(String projectId,String startTime) throws ParseException {
    long str = Long.valueOf(DateUtil.dateToStamp(startTime));
    Project project = projectMapper.queryProjectByProId(projectId);
    //查询项目是否有变压器
    int transformerCount = deviceMapper.queryTransformer(projectId);
    if(transformerCount == 0){
      return new HashMap();
    }
    List<PowerdataTiming> list=new ArrayList<>();
    Map map=new HashMap();
    Map maps=new HashMap();
    List data = new ArrayList();
    List datas = new ArrayList();
    Map mapdata=new HashMap();

    DateTimeUtils dateTimeUtils = new DateTimeUtils();
    List<Device> lists = deviceMapper.getDeviceByProjectId(projectId);
    List<TemperatureDevice> temperatureDeviceList = temperatureDeviceMapper.getTemperatureDeviceByProjectId(projectId);
    List<TemperatureDevice> getTemperatureDeviceLike = temperatureDeviceMapper.getTemperatureDeviceLike();

    PowerdataTiming powerdataTimings = new PowerdataTiming();
    float sum=0;
    float totalSum=0;
    double ptf=0;
    //判断是否为本月，如果是，则查询当天数据添加至list
    if(DateUtil.isThisMonth(str)){
      //判断是否为金控设备 1大岛 2金控
      if(Integer.parseInt(project.getPowerDaraFlag()) == 1){
/*          for (Device device : lists) {
             if(device.getDeviceName().contains("变压器")){
               Powerdata powerData=powerdataMapper.queryPowerDataDeviceDay(device.getTableName(),device.getSerialNumber());
               if(powerData != null){
                 sum=sum+powerData.getForwardActiveTotalElectricalEnergy();
                 totalSum=totalSum+powerData.getTotalReverseActiveEnergy();
                 powerdataTimings.setCreatetime(dateTimeUtils.getFormat(powerData.getCreatetime()));
                 powerdataTimings.setMaxPtf(powerData.getMax_ptf());
                 }
               }
            }
            powerdataTimings.setForwardActiveTotalElectricalEnergy(sum);
            powerdataTimings.setTotalReverseActiveEnergy(totalSum);*/

      }else {
        //判断表中是否有变压器，如果有则只差变压器，没有则查询全部设备相加
            if(getTemperatureDeviceLike.size() !=0){
              for (TemperatureDevice temperatureDevice : getTemperatureDeviceLike) {
                TemperatureData temperatureData = temperatureDataMapper.queryeTemperatureByDeviceId(temperatureDevice.getTableName(), temperatureDevice.getSerialNumber());
                if (temperatureData != null) {
                  sum = sum + temperatureData.gettActiveEnergy();
                  totalSum = totalSum + temperatureData.gettReactiveEnergy();
                  powerdataTimings.setCreatetime(dateTimeUtils.getFormat(temperatureData.getCreateTime()));
                  powerdataTimings.setMaxPtf(temperatureData.getMax_ptf());
                }
              }
            }else {
              for (TemperatureDevice temperatureDevice : temperatureDeviceList) {
                TemperatureData temperatureData = temperatureDataMapper.queryeTemperatureByDeviceId(temperatureDevice.getTableName(), temperatureDevice.getSerialNumber());
                if (temperatureData != null) {
                  sum = sum + temperatureData.gettActiveEnergy();
                  totalSum = totalSum + temperatureData.gettReactiveEnergy();
                  powerdataTimings.setCreatetime(dateTimeUtils.getFormat(temperatureData.getCreateTime()));
                  powerdataTimings.setMaxPtf(temperatureData.getMax_ptf());
                }
              }
            }

        powerdataTimings.setForwardActiveTotalElectricalEnergy(sum);
        powerdataTimings.setTotalReverseActiveEnergy(totalSum);
      }
    }

    //判断是否为金控设备 1大岛 2金控
    if(Integer.parseInt(project.getPowerDaraFlag()) == 1){
       list = powerdataTimingMapper.queryePowerdataTiming(projectId,startTime);
    }else {
      list = powerdataTimingMapper.queryeNotLike(projectId,startTime);
    }

    /*    //判断是否本月 如果是则添加，不然报null
        if(DateUtil.isThisMonth(str)){
            list.add(powerdataTimings);
        }*/
    if(list.size() == 0){
      return map;
    }

    int count = 0;

    for (PowerdataTiming powerdataTiming : list) {
      if(powerdataTiming.getTotalReverseActiveEnergy() == null){
        powerdataTiming.setTotalReverseActiveEnergy(Float.parseFloat("0"));
      }
      count++;
      mapdata=new HashMap();
      mapdata.put("createtime",powerdataTiming.getCreatetime());
      mapdata.put("forwardActiveTotalElectricalEnergy",powerdataTiming.getForwardActiveTotalElectricalEnergy());
      mapdata.put("totalReverseActiveEnergy",powerdataTiming.getTotalReverseActiveEnergy());
      mapdata.put("ptf",powerdataTiming.getMaxPtf());
      data.add(mapdata);
    }
    map.put("list",data);


    //有功电能排序
    Collections.sort(list,new Comparator<PowerdataTiming>() {
      @Override
      public int compare(PowerdataTiming o1, PowerdataTiming o2) {
        // TODO Auto-generated method stub
        return o2.getForwardActiveTotalElectricalEnergy().intValue() - o1.getForwardActiveTotalElectricalEnergy().intValue() ;
      }
    });
    sum=0;
    maps.put("max",list.get(0).getForwardActiveTotalElectricalEnergy());
    maps.put("maxTime",list.get(0).getCreatetime());
    maps.put("min",list.get(list.size()-1).getForwardActiveTotalElectricalEnergy());
    maps.put("minTime",list.get(list.size()-1).getCreatetime());
    for (PowerdataTiming powerdataTiming : list) {
      sum=sum+powerdataTiming.getForwardActiveTotalElectricalEnergy();
    }
    maps.put("avg",sum/count);
    maps.put("name","有功电能(kW·h)");
    datas.add(maps);


    //无功电能排序
    Collections.sort(list,new Comparator<PowerdataTiming>() {
      @Override
      public int compare(PowerdataTiming o1, PowerdataTiming o2) {
        // TODO Auto-generated method stub
        return o2.getTotalReverseActiveEnergy().intValue() - o1.getTotalReverseActiveEnergy().intValue() ;
      }
    });
    maps= new HashMap();
    totalSum=0;
    maps.put("max",list.get(0).getTotalReverseActiveEnergy());
    maps.put("maxTime",list.get(0).getCreatetime());
    maps.put("min",list.get(list.size()-1).getTotalReverseActiveEnergy());
    maps.put("minTime",list.get(list.size()-1).getCreatetime());
    for (PowerdataTiming powerdataTiming : list) {
      System.out.println(powerdataTiming.getTotalReverseActiveEnergy());
      totalSum=totalSum+powerdataTiming.getTotalReverseActiveEnergy();
    }
    maps.put("avg",totalSum/count);
    maps.put("name","无功电能(kW·h)");
    datas.add(maps);


    //功率因数排序
    Collections.sort(list,new Comparator<PowerdataTiming>() {
      @Override
      public int compare(PowerdataTiming o1, PowerdataTiming o2) {
        if(o1.getMaxPtf()==null){
          o1.setMaxPtf(Float.parseFloat("0"));
        }
        if(o2.getMaxPtf()==null){
          o2.setMaxPtf(Float.parseFloat("0"));
        }
        // TODO Auto-generated method stub
        return o2.getMaxPtf().intValue() - o1.getMaxPtf().intValue() ;
      }
    });
    maps= new HashMap();
    maps.put("max",list.get(0).getMaxPtf());
    maps.put("maxTime",list.get(0).getCreatetime());
    maps.put("min",list.get(list.size()-1).getMaxPtf());
    maps.put("minTime",list.get(list.size()-1).getCreatetime());
    if(sum == 0  && totalSum == 0){
      ptf=0;
    }else {
       ptf = ElectricityFeesUtils.getAveragePowerFactor(sum,totalSum);
    }

    maps.put("avg",ptf);
    maps.put("name","功率因数");
    datas.add(maps);

    map.put("table",datas);
    return map;
  }



}

